import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CyclicBarrierTest2 {
   public static void main(String[] args) {
    ExecutorService service = Executors.newFixedThreadPool(5);
    CyclicBarrier barrier = new CyclicBarrier(5, () -> {
        System.out.println("哪个猪最快...");
    });
    
    // 循环3次
    for (int i = 0;i < 3; i++) {
        // 5个猪
        for (int j = 0; j < 5;j++) {
            int finalJ = j;
            service.submit(() -> {
                System.out.println("pig" + finalJ + " is running .....");
                try {
                    //随机时间，模拟跑的时间
                    Thread.sleep(new Random().nextInt(5000));
                    System.out.println("pig " + finalJ + " reaches barrier...");
                    barrier.await();
                } catch(InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
        }
    }
    service.shutdown();
   }
}
